import java.util.HashMap;



/**
 * @Description
 *      对象的复用性，在项目中如果需要用到大量相似的对象，则可以将这些对象相同的部分抽象出来
 *      然后只改变不同的地方，返回调用者使用
 *
 *      案例中需要画出不同坐标的切不同颜色的圆，则坐标是不确定的，但是颜色的种类相对较少
 *      则每次需要新的图形的时候先判断此种颜色的对象是否已经存在，如果存在只需要改变其坐标返回即可
 *      若不存在则创建合适的对象并保存起来供下次调用时使用
 *
 * @Date 15:58 2022/8/23
 * @Author sunye
 **/
public class FlyweightPatternDemo extends ShapeFactory {
    private static final String colors[] =
            { "Red", "Green", "Blue", "White", "Black" };
    public static void main(String[] args) {

        for(int i=0; i < 20; ++i) {
            Circle circle =
                    (Circle)ShapeFactory.getCircle(getRandomColor());
            circle.setX(getRandomX());
            circle.setY(getRandomY());
            circle.setRadius(100);
            circle.draw();
        }
    }
    private static String getRandomColor() {
        return colors[(int)(Math.random()*colors.length)];
    }
    private static int getRandomX() {
        return (int)(Math.random()*100 );
    }
    private static int getRandomY() {
        return (int)(Math.random()*100);
    }
}

interface Shape {
    void draw();
}

class Circle implements Shape {
    private String color;
    private int x;
    private int y;
    private int radius;

    public Circle(String color){
        this.color = color;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setRadius(int radius) {
        this.radius = radius;
    }

    @Override
    public void draw() {
        System.out.println("Circle: Draw() [Color : " + color
                +", x : " + x +", y :" + y +", radius :" + radius);
    }
}

class ShapeFactory extends Circle {
    private static final HashMap<String, Shape> circleMap = new HashMap<>();

    public static Shape getCircle(String color) {
        Circle circle = (Circle)circleMap.get(color);

        if(circle == null) {
            circle = new Circle(color);
            circleMap.put(color, circle);
            System.out.println("Creating circle of color : " + color);
        }
        return circle;
    }
}
